#include "ThreadPool.h"

const int TASK_MAX_NUM = 1024;

ThreadPool::ThreadPool(): 
    initThreadNum_(4),
    taskNum_(0),
    taskQueMaxThreshold_(TASK_MAX_NUM),
    stop_(false) {
}


ThreadPool::~ThreadPool() {
    // 关闭线程池
    stop_ = true;
    notEmpty_.notify_all();
    for (std::shared_ptr<std::thread>& t : threads_) {
        t->join();
    }
}



void ThreadPool::start(int initThreadNum) {
    initThreadNum_ = initThreadNum;
    std::cout << "[Thread Pool] Number of threads are set to " << initThreadNum_ << '.' << std::endl;
    // 创建线程
    for (int i=0; i < initThreadNum_; ++i){
        std::shared_ptr<std::thread> ptr = std::make_shared<std::thread>(&ThreadPool::threadFunc, this);
        threads_.emplace_back(std::move(ptr));
    }
}


void ThreadPool::threadFunc() {
    for (;;) {
        std::unique_lock<std::mutex> ulock(taskQueMtx_);

        notEmpty_.wait(ulock, [&]() -> bool {return !taskQue_.empty() || stop_;});

        if (taskQue_.empty() && stop_) return ;

        std::shared_ptr<Task> task = taskQue_.front();
        taskQue_.pop();
        --taskNum_;
        notFull_.notify_one();

        ulock.unlock();
        (*task)();
    }
        
}



